﻿using System;
using System.Collections.Generic;
using Netbits.TelnetServer.Enums;

namespace Netbits.TelnetServer
{
	/// <summary>
	/// Helperclass for print attribute-list sequentially
	/// </summary>
	public class PrintAttributeList
	{
		#region Private Variables

		readonly NetbitsTelnetClientSession _Client;
		readonly List<KeyValuePair<string, string>> _Attributes;

		#endregion

		#region Constructor

		internal PrintAttributeList( NetbitsTelnetClientSession Client_ )
		{
			_Attributes = new List<KeyValuePair<string, string>>();
			_Client = Client_;
		}

		#endregion

		#region Public Functions

		/// <summary>
		/// Add new attribute with value
		/// </summary>
		/// <param name="Name_">name of the attribute</param>
		/// <param name="Value_">value of the attribute</param>
		/// <param name="Parameters_">parameter for string.format (value)</param>
		public void Add( string Name_, string Value_, params object[] Parameters_ )
		{
			string value = Value_;
			if( Parameters_ != null || Parameters_.Length > 0 )
				value = string.Format( value, Parameters_ );

			_Attributes.Add( new KeyValuePair<string, string>( Name_, value ) );
		}

		/// <summary>
		/// Print the full attribute list
		/// </summary>
		public void Print()
		{
			int maxNameLength = 0;
			foreach( KeyValuePair<string, string> kvp in _Attributes )
			{
				if( kvp.Key.Length > maxNameLength )
					maxNameLength = kvp.Key.Length;
			}

			int maxValueLength = _Client.ClientWidth - maxNameLength - 3;

			string printLine = string.Empty;
			printLine += _Client.GetAttribute( EnumTelnetColors.Blue, EnumTelnetColors.Nothing, EnumTelnetAttributes.Dim );
			printLine += "{0}";
			printLine += _Client.GetResetColorAttributes();
			printLine += " - ";
			printLine += _Client.GetAttribute( EnumTelnetColors.Green, EnumTelnetColors.Nothing, EnumTelnetAttributes.Bright );
			printLine += "{1}";
			printLine += _Client.GetResetColorAttributes();

			try
			{
				_Client.PrintLock.EnterWriteLock();

				foreach( KeyValuePair<string, string> kvp in _Attributes )
					_Client.Send( printLine, true, kvp.Key.PadLeft( maxNameLength ), kvp.Value.PadRight( maxValueLength ) );
			}
			finally
			{
				_Client.PrintLock.ExitWriteLock();
			}
		}

		#endregion
	}
}
